#define __LIBRARY__

#include <unistd.h>

static inline _syscall0(int, fork);

int errno;

#include <linux/tty.h>
#include <linux/kernel.h>
#include <mystdio.h>
#include <linux/sched.h>
#include <asm/system.h>

extern void mem_init(long start, long end);
	
#define EXT_MEM_K (*(unsigned short *)0x90002)
	
static long memory_end = 0;
static long buffer_memory_end = 0;
static long main_memory_start = 0;

void main(void)
{

        struct BOOTINFO *binfo;
        binfo = (struct BOOTINFO *) ADR_BOOTINFO;

	memory_end = (1<<20) + (EXT_MEM_K<<10);
	memory_end &= 0xfffff000;
	    if (memory_end > 16*1024*1024){
	        memory_end = 16*1024*1024;
                //myprint(message);
            }
	    if (memory_end > 12*1024*1024){
	        buffer_memory_end = 4*1024*1024;
                //myprint(message2);
            }
	    else if (memory_end > 6*1024*1024){
	        buffer_memory_end = 2*1024*1024;
                //myprint(message3);
            }
	    else{
	        buffer_memory_end = 1*1024*1024;
                //myprint(message4);
            }
	
	    main_memory_start = buffer_memory_end;
	    mem_init(main_memory_start, memory_end);

   init_fstdio(binfo->xsize, binfo->ysize);
   trap_init();
   sched_init();
   tty_init();
  /*printm(0, binfo->xsize, binfo->ysize, 500/8, 200/16, PURPLE, 
    "He is %d %d %d\r\n", 28, binfo->xsize, binfo->ysize);*/
  
  //sti();
   
  printm(0, binfo->xsize, binfo->ysize, 500/8, 200/16, PURPLE, "He is %d", 28);
  printm(0, binfo->xsize, binfo->ysize, 500/8, 300/16, DARKBLUE, 
     "Memory start: %d, memory_end: %d", main_memory_start,  memory_end);

   move_to_user_mode();
/*   __asm__ __volatile__(
           //"int $0x7f\n\r"
           "int $0x80\n\r"
           "int $0x80\n\r"
           "int $0x80\n\r"
           "int $0x80\n\r"
           "int $0x80\n\r"
           "int $0x80\n\r"
           "movl $30, %%eax\n\r"
           "movl $0, %%ebx\n\r"
           "divl %%ebx\n\r"
           "loop:\n\r"
           "jmp loop"
           ::);
*/
        int pid=fork();
        if (pid == 0) {
           printm(0, 1024, 768, 70, 20, PURPLE, "%d", pid);
           test_b();
         }
         else {
           printm(0, 1024, 768, 75, 20, BLACK, "%d", pid);
           test_a();
         }
  while (1) {
  }
}
